/*Hm9gUKDDwtNjV7Mk8onAztUHq1J91LIC2ncuaDAP/5puoLckI554fGMgKidJrsa5*/
import { ajax, base, toast, cacheTools, printer, cardCache, promptBox } from 'nc-lightapp-front';
import { billType, tradeType, dataSource, searchId, tableId } from '../constants';
import { headButton } from '../../../../public/components/pubUtils/buttonName';
import { getTransferInfo } from '../../../../public/components/pubUtils/transferButtonUtil.js';
import { imageScan, imageView } from 'sscrp/rppub/components/image';
import arapLinkReport from '../../../../public/components/arapBillLinkReport.js';
import linkvouchar from '../../../../public/components/linkvouchar.js';
import madeBill from '../../../../public/components/madeBill.js';
import { loginContext, getContext, loginContextKeys } from '../../../../public/components/arapInitInfo/loginContext';
import { batchGenerate } from '../../../../public/components/pubUtils/billPubUtil.js';
import { moduleEnable, IMAG, SSCIVM } from '../../../../public/components/moduleEnable.js';

let { setDefData, getDefData } = cardCache;

export default function buttonClick(props, id) {
	let code = getContext(loginContextKeys.transtype);
	let appcode = props.getSearchParam('c');
	let pagecode = props.getSearchParam('p');
	this.dataInSaga.butncode = id;
	switch (id) {
		case headButton.Add:
			pagecode = getDefData('sessionTradeType', dataSource);
			if (code) {
				pagecode = code;
			} else if (!pagecode) {
				pagecode = tradeType;
			}
			props.pushTo('/card', {
				status: 'add',
				pagecode: pagecode
			});
			break;
		case headButton.Commit: // 批量提交
			commitOpreration(this, this.props, this.tableId, billType, headButton.Commit);
			break;
		case headButton.Uncommit: // 批量收回
			commitOpreration(this, this.props, this.tableId, billType, headButton.Uncommit);
			break;
		case headButton.Generate://生成
			batchGenerate(this)
			break;
		case headButton.Delete:
			promptBox({
				color: 'warning',
				title: this.state.json['gatheringbill-000005'] /* 国际化处理： 删除*/,
				content: this.state.json['gatheringbill-000079'] /* 国际化处理： ​确定要删除所选数据吗？*/,
				noFooter: false,
				noCancelBtn: false,
				beSureBtnName: this.state.json['gatheringbill-000004'] /* 国际化处理： 确定*/,
				cancelBtnName: this.state.json['gatheringbill-000002'] /* 国际化处理： 取消*/,
				beSureBtnClick: () => {
					let delObjs = getAllCheckedData.call(this, this.props, this.tableId, billType);
					if (delObjs.length == 0) {
						toast({
							color: 'warning',
							content: this.state.json['gatheringbill-000010']
						}); /* 国际化处理： 请选中至少一行数据!*/
						return;
					}
					if (delObjs.length == 1) {
						this.Info.pk_bill = delObjs[0].pk_bill;
						this.Info.ts = delObjs[0].ts;
						this.Info.index = delObjs[0].index;
						this.delConfirm();
					} else {
						ajax({
							url: '/nccloud/arap/arappub/delete.do',
							data: delObjs,
							success: (res) => {
								let { success, data } = res;
								if (success) {
									if (data) {
										toast({
											duration: 'infinity',
											color: data.PopupWindowStyle,
											content: data.errMsg
										});
										//删除当前行数据
										props.table.deleteTableRowsByIndex(tableId, data.successIndexs);
										//删除缓存数据
										props.table.deleteCacheId(tableId, data.successPKs);
										//删行之后控制肩部按钮
										this.onSelected();
									}
								}
							}
						});
					}
				}
			});

			break;
		case headButton.LinkAprv: //审批详情
			let LinkAprvData = this.props.table.getCheckedRows(this.tableId)[0];
			if (LinkAprvData) {
				this.Info.pk_tradetype = LinkAprvData.data.values.pk_tradetype.value;
				this.Info.pk_bill = LinkAprvData.data.values.pk_gatherbill.value;
				this.setState({
					showApproveDetail: true
				});
			} else {
				toast({ color: 'warning', content: this.state.json['gatheringbill-000050'] }); /* 国际化处理： 请选中一行数据!*/
			}
			break;

		case headButton.MadeBill: //制单
			madeBill(
				this,
				props,
				this.props.table.getCheckedRows(this.tableId),
				'pk_gatherbill',
				props.getSearchParam('c'),
				true
			);
			break;
		case headButton.LinkSettleInfo: //结算信息
			let settleInfoData = getFirstCheckedData(this.props, this.tableId);
			ajax({
				url: '/nccloud/arap/arappub/linksettleinfo.do',
				data: Object.assign({
					pk_bill: settleInfoData.data.values.pk_gatherbill.value,
					billType: billType
				}, this.dataInSaga),
				success: (res) => {
					let { success, data } = res;
					if (success) {
						props.openTo('/nccloud/resources/cmp/settlementmanagement/settlement/main/index.html#/card', {
							status: 'browse',
							srcid: settleInfoData.data.values.pk_gatherbill.value,
							src: '2006',
							appcode: '360704SM',
							pagecode: '360704SM_C01'
						});
					}
				},
				error: function (data) {
					toast({ color: 'warning', content: data.message });
				}
			});
			break;
		case headButton.ConnectSettleInfo: //关联结算信息
			ajax({
				url: '/nccloud/arap/arappub/validatecmp.do',
				async: false,
				data: null,
				success: (res) => {
					if (res.success) {
						pagecode = getDefData('sessionTradeType', dataSource);
						if (code) {
							pagecode = code;
						} else if (!pagecode) {
							pagecode = tradeType;
						}
						props.openTo('/nccloud/resources/cmp/settlementmanagement/settlepublic/list/index.html', {
							appcode: '360704SM',
							pagecode: '360704SMP_L01',
							callbackappcode: props.getSearchParam('c'),
							callbackpagecode: pagecode,
							src: '0',
							callback: '/nccloud/resources/arap/gatheringbill/gatheringbill/main/index.html#/card'
						});
					}
				}
			});

			break;
		case headButton.LinkInformer: //到账通知
			let InformerInfo = getFirstCheckedData(this.props, this.tableId);
			ajax({
				url: '/nccloud/arap/arappub/linkinformer.do',
				data: Object.assign({
					pk_bill: InformerInfo.data.values.pk_gatherbill.value,
					billType: this.billType
				}, this.dataInSaga),
				success: (res) => {
					if (res.success && res.data) {
						let length = res.data.length;
						if (length == 1) {
							props.openTo('/nccloud/resources/cmp/informer/LinkBill/card/index.html', {
								appcode: '36070AISC',
								pagecode: '36070AILLINK',
								status: 'browse',
								id: res.data
							});
						} else {
							props.openTo('/nccloud/resources/cmp/informer/LinkBill/list/index.html', {
								appcode: '36070AISC',
								pagecode: '36070AICLINK',
								status: 'browse',
								ids: res.data
							});
						}
					}
				}
			});
			break;
		case headButton.LinkBal: //联查余额表
			arapLinkReport(
				this.props,
				getFirstCheckedData(this.props, this.tableId).data.values.pk_gatherbill.value,
				billType,
				getFirstCheckedData(this.props, this.tableId).data.values.objtype.value
			);
			break;
		case headButton.LinkDeal: //联查处理情况
			let dealInfo = getFirstCheckedData(this.props, this.tableId);
			ajax({
				url: '/nccloud/arap/arappub/linkdeal.do',
				data: Object.assign({
					pk_bill: dealInfo.data.values.pk_gatherbill.value,
					billType: billType
				}, this.dataInSaga),
				success: (res) => {
					if (res.success) {
						//打开处理情况模态框
						let data = res.data;
						//当前选中数据的第一行的交易类型和单据号，用于联查处理情况的模态框上面的显示
						let checkedData = this.props.table.getCheckedRows(this.tableId)[0].data.values;
						this.Info.combinedExaminationData = data;
						this.Info.pk_tradetypeid = checkedData.pk_tradetypeid
							? checkedData.pk_tradetypeid.display
							: null;
						this.Info.billno = checkedData.billno ? checkedData.billno.value : null;
						this.handleCombined();
					}
				}
			});
			break;
		case headButton.LinkVouchar: //联查凭证
			let voucharInfo = getFirstCheckedData(this.props, this.tableId);
			linkvouchar(
				this,
				props,
				voucharInfo,
				voucharInfo.data.values.pk_gatherbill.value,
				props.getSearchParam('c')
			);
			break;
		case headButton.LinkConfer: //联查协同单据
			let conferInfo = getFirstCheckedData(this.props, this.tableId);
			ajax({
				url: '/nccloud/arap/arappub/linkconfer.do',
				async: false,
				data: Object.assign({
					pk_bill: conferInfo.data.values.pk_gatherbill.value,
					billType: billType
				}, this.dataInSaga),
				success: (res) => {
					let data = res.data;
					if (data) {
						props.openTo(data.url, data.condition);
					}
				}
			});
			break;
		case headButton.LinkTbb: //联查计划预算
			let tbbInfo = getFirstCheckedData(this.props, this.tableId);
			ajax({
				url: '/nccloud/arap/arappub/linktbb.do',
				data: Object.assign({
					pk_bill: tbbInfo.data.values.pk_gatherbill.value,
					billType: billType
				}, this.dataInSaga),
				success: (res) => {
					this.Info.tbbLinkSourceData = res.data;
					this.setState({
						isTbbLinkshow: true
					});
				}
			});
			break;
		case headButton.BillLinkQuery: //联查单据
			let selectData = getFirstCheckedData(this.props, this.tableId);
			this.Info.pk_bill = selectData.data.values.pk_gatherbill.value;
			this.Info.pk_tradetype = selectData.data.values.pk_tradetype.value;
			this.setState({
				showBillTrack: true
			});
			break;
		case 'Print': //打印
			selectData = this.props.table.getCheckedRows(this.tableId);
			if (selectData.length == 0) {
				toast({ color: 'warning', content: this.state.json['gatheringbill-000050'] }); /* 国际化处理： 请选中一行数据!*/
				return;
			}
			let pk_bills = [];
			selectData.forEach((val) => {
				pk_bills.push(val.data.values?val.data.values.pk_gatherbill.value:val.data.pk);
			});
			this.printData.oids = pk_bills;
			this.printData.nodekey = 'card';
			this.onPrint();
			break;
		case headButton.PrintList: //打印列表
			selectData = this.props.table.getCheckedRows(this.tableId);
			pk_bills = [];
			selectData.forEach((val) => {
				pk_bills.push(val.data.values?val.data.values.pk_gatherbill.value:val.data.pk);
			});
			if (pk_bills.length == 0) {
				toast({ color: 'warning', content: this.state.json['gatheringbill-000050'] }); /* 国际化处理： 请选中一行数据!*/
				return;
			}
			this.printData.oids = pk_bills;
			this.printData.nodekey = 'list';
			printer(
				'pdf', //支持两类: 'html'为模板打印, 'pdf'为pdf打印
				'/nccloud/arap/arappub/print.do', //后台服务url
				this.printData
			);
			break;
		case headButton.Output: //打印输出
			selectData = this.props.table.getCheckedRows(this.tableId);
			if (selectData.length == 0) {
				toast({ color: 'warning', content: this.state.json['gatheringbill-000050'] }); /* 国际化处理： 请选中一行数据!*/
				return;
			}
			pk_bills = [];
			selectData.forEach((val) => {
				pk_bills.push(val.data.values.pk_gatherbill.value);
			});
			this.outputData.oids = pk_bills;
			this.outputData.nodekey = 'card';
			this.printOutput();
			break;
		case headButton.OfficalPrint: //正式打印
			selectData = this.props.table.getCheckedRows(this.tableId);
			if (selectData.length == 0) {
				toast({ color: 'warning', content: this.state.json['gatheringbill-000050'] }); /* 国际化处理： 请选中一行数据!*/
				return;
			}
			pk_bills = [];
			selectData.forEach((val) => {
				pk_bills.push(val.data.values.pk_gatherbill.value);
			});
			this.printData.oids = pk_bills;
			this.printData.nodekey = 'card';
			this.officalPrintOutput();
			break;
		case headButton.CancelPrint: //取消正式打印
			selectData = this.props.table.getCheckedRows(this.tableId);
			if (selectData.length == 0) {
				toast({ color: 'warning', content: this.state.json['gatheringbill-000050'] }); /* 国际化处理： 请选中一行数据!*/
				return;
			}
			pk_bills = [];
			selectData.forEach((val) => {
				pk_bills.push(val.data.values.pk_gatherbill.value);
			});
			this.printData.oids = pk_bills;
			this.printData.nodekey = 'card';
			this.cancelPrintOutput();
			break;
		case headButton.ExportData: //导出
			if (this.state.forceRender) {
				this.setState({ forceRender: false })
			}
			selectData = this.props.table.getCheckedRows(this.tableId);
			pk_bills = [];
			selectData.forEach((val) => {
				pk_bills.push(val.data.values.pk_gatherbill.value);
			});
			if (pk_bills.length == 0) {
				toast({ color: 'warning', content: this.state.json['gatheringbill-000050'] }); /* 国际化处理： 请选中一行数据!*/
				return;
			}
			this.Info.selectedPKS = pk_bills; //传递主键数组,之前nc需要导出的加主键
			this.props.modal.show('exportFileModal'); //不需要导出的只执行这行代码
			break;
		case headButton.Refresh: //导出
			let data = getDefData(searchId, dataSource);
			if (data) {
				ajax({
					url: '/nccloud/arap/gatheringbill/query.do',
					data: data,
					success: (res) => {
						let { success, data } = res;
						if (success) {
							if (data) {
								toast({
									color: 'success',
									title: this.state.json['gatheringbill-000078']
								}); /* 国际化处理： 刷新成功*/
								this.props.table.setAllTableData(this.tableId, data[this.tableId]);
							} else {
								toast({
									color: 'success',
									content: this.state.json['gatheringbill-000011']
								}); /* 国际化处理： 未查询到数据*/
								this.props.table.setAllTableData(this.tableId, { rows: [] });
							}
						}
						setDefData(this.tableId, dataSource, data); //放入缓存
						this.onSelected();
					}
				});
			} else {
				toast({ color: 'success', title: this.state.json['gatheringbill-000078'] }); /* 国际化处理： 刷新成功*/
				this.props.table.setAllTableData(this.tableId, { rows: [] });
			}
			break;
		case headButton.ReceiptCheck: //影像查看pk_tradetype
			if (!moduleEnable(this, IMAG)) { //校验关联模块是否启用
				return;
			}
			let CheckInfo = getFirstCheckedData(this.props, this.tableId);
			// let pk_tradetype = CheckInfo.data.values.pk_tradetype.value;
			// let openShowbillid = CheckInfo.data.values.pk_payablebill.value;
			// ajax({
			// 	url: '/nccloud/arap/payablebill/querycard.do',
			// 	data: {
			// 		pk_bill: openShowbillid
			// 	},
			// 	success: (res) => {
			// 		if (res.data) {
			// 			imageView(res.data, openShowbillid, pk_tradetype, 'iweb');
			// 		}
			// 	}
			// });
			var billInfoMap = {};

			//基础字段 单据pk,单据类型，交易类型，单据的组织
			billInfoMap.pk_billid = CheckInfo.data.values.pk_gatherbill.value;
			billInfoMap.pk_billtype = CheckInfo.data.values.pk_billtype.value;
			billInfoMap.pk_tradetype = CheckInfo.data.values.pk_tradetype.value;
			billInfoMap.pk_org = CheckInfo.data.values.pk_org.value;
			imageView(billInfoMap, 'iweb');
			break;
		case headButton.ReceiptScan: //影像扫描
			if (!moduleEnable(this, IMAG)) { //校验关联模块是否启用
				return;
			}
			let ScanInfo = getFirstCheckedData(this.props, this.tableId);
			// let tradetype = ScanInfo.data.values.pk_tradetype.value;
			// let openbillid = ScanInfo.data.values.pk_payablebill.value;
			// ajax({
			// 	url: '/nccloud/arap/payablebill/querycard.do',
			// 	data: {
			// 		pk_bill: openbillid
			// 	},
			// 	success: (res) => {
			// 		if (res.data) {
			// 			imageScan(res.data, openbillid, tradetype, 'iweb');
			// 		}
			// 	}
			// });
			var billInfoMap = {};

			//基础字段 单据pk,单据类型，交易类型，单据的组织
			billInfoMap.pk_billid = ScanInfo.data.values.pk_gatherbill.value;
			billInfoMap.pk_billtype = ScanInfo.data.values.pk_billtype.value;
			billInfoMap.pk_tradetype = ScanInfo.data.values.pk_tradetype.value;
			billInfoMap.pk_org = ScanInfo.data.values.pk_org.value;

			//影像所需 FieldMap
			billInfoMap.BillType = ScanInfo.data.values.pk_tradetype.value;
			billInfoMap.BillDate = ScanInfo.data.values.creationtime.value;
			billInfoMap.Busi_Serial_No = ScanInfo.data.values.pk_gatherbill.value;
			// billInfoMap.pk_billtype = billdata.head.head.rows[0].values.pk_billtype.value;
			billInfoMap.OrgNo = ScanInfo.data.values.pk_org.value;
			billInfoMap.BillCode = ScanInfo.data.values.billno.value;
			billInfoMap.OrgName = ScanInfo.data.values.pk_org_v.display;
			billInfoMap.Cash = ScanInfo.data.values.money.value;
			imageScan(billInfoMap, 'iweb');
			break;
		case headButton.AttachManage:
			let AttachInfo = getFirstCheckedData(this.props, this.tableId);
			this.Info.pk_bill = AttachInfo.data.values.pk_gatherbill.value;
			this.Info.billno = AttachInfo.data.values.billno.value;
			this.setState({
				showUploader: true,
				target: null
			});
			break;
		case headButton.Refund://退款
			billRefund.call(this, this.props)
			break;
		case headButton.CancelRefund://取消退款
			billCancelRefund.call(this, this.props)
			break;
		default:
			let transferInfo = getTransferInfo(this, id);
			if (transferInfo) {
				ajax({
					url: '/nccloud/arap/arappub/queryrelatedapp.do',
					data: {
						billType: transferInfo.src_billtype,
						transTypes:transferInfo.transtypes
					},
					success: (res) => {
						if (res) {
							//将业务流程放入缓存
							setDefData(
								transferInfo.src_billtype + transferInfo.transtypes[0],
								'transfer.dataSource',
								transferInfo.busitypes
							);
							let dest_tradetype = getDefData('sessionTradeType', dataSource);
							if (code) {
								dest_tradetype = code;
							} else if (!dest_tradetype) {
								dest_tradetype = tradeType;
							}
							let url = '/' + transferInfo.src_billtype;
							props.pushTo(url, {
								src_appcode: res.data.appcode,
								src_tradetype: transferInfo.transtypes[0], //来源交易类型
								dest_billtype: billType,
								dest_tradetype: dest_tradetype
							});
						}
					}
				});
			}
			break;
	}
}

//获取选中数据的第一行,选中多行的时候只取第一行数据
let getFirstCheckedData = function (props, tableId) {
	let checkedData = props.table.getCheckedRows(tableId);
	let checkedObj;
	if (checkedData.length > 0) {
		checkedObj = checkedData[0];
	} else {
		toast({ color: 'warning', content: this.state.json['gatheringbill-000050'] }); /* 国际化处理： 请选中一行数据!*/
		return;
	}
	return checkedObj;
};

//获取选中数据的id和billType
let getAllCheckedData = function (props, tableId, billType) {
	let checkedData = props.table.getCheckedRows(tableId);
	let checkedObj = [];
	checkedData.forEach((val) => {
		checkedObj.push(Object.assign({
			pk_bill: val.data.values?val.data.values.pk_gatherbill.value:val.data.pk,
            ts: val.data.values?val.data.values.ts.value:val.data.ts,
			billType: billType,
			index: val.index,
			pageId: props.getSearchParam('p')
		}, this.dataInSaga));
	});
	return checkedObj;
};

let getAllCheckedIndex = function (props, tableId, billType) {
	let checkedData = props.table.getCheckedRows(tableId);
	let indexs = [];
	indexs.forEach((val) => {
		indexs.push(val.index);
	});
	return indexs;
};
let commitOpreration = function (that, props, tableId, billType, actionType) {
	let commitParams = getAllCheckedData.call(that, props, tableId, billType);
	if (commitParams.length == 0) {
		toast({ color: 'warning', content: this.state.json['gatheringbill-000010'] }); /* 国际化处理： 请选中至少一行数据!*/
		return;
	}
	let ajaxUrl = '';
	if (actionType == headButton.Commit) {
		ajaxUrl = '/nccloud/arap/arappub/batchcommit.do';
	} else if (actionType == headButton.Uncommit) {
		ajaxUrl = '/nccloud/arap/arappub/batchuncommit.do';
	}
	if (commitParams.length == 1 && actionType == headButton.Commit) {
		//单条的时候走单条的处理
		that.Info.tipUrl = '/nccloud/arap/arappub/commit.do';
		that.Info.record = props.table.getCheckedRows(tableId)[0].data.values;
		that.Info.record.numberindex = { scale: 0, value: commitParams[0].index + 1 };
		that.commitAndUncommit();
		return;
	}

	ajax({
		url: ajaxUrl,
		data: commitParams,
		success: (res) => {
			let { success, data } = res;
			if (success) {
				if (data.grid) {
					let grid = data.grid;
					let updateValue = [];
					for (let key in grid) {
						updateValue.push({ index: key, data: { values: grid[key].values } });
					}
					props.table.updateDataByIndexs(tableId, updateValue);
				}

				if (data.message) {
					toast({
						duration: 'infinity',
						color: data.PopupWindowStyle,
						content: data.message
					});
					that.onSelected();
				}
			}
		}
	});
};
export function billRefund(props) {
	let that = this
	let refundData = getAllCheckedData.call(this, this.props, this.tableId, billType);//选中表体行数据信息
	ajax({
		url: '/nccloud/arap/arappub/listrefund.do',
		data: refundData,
		success: (res) => {
			let { success, data } = res;
			if (success) {
				if (data.grid) {
					let grid = data.grid;
					let updateValue = [];
					for (let key in grid) {
						updateValue.push({ index: key, data: { values: grid[key].values } });
					}
					props.table.updateDataByIndexs(tableId, updateValue);
				}
				if (data.message) {
					toast({
						duration: 'infinity',
						color: data.PopupWindowStyle,
						content: data.message
					});
					that.onSelected();
				}
			}
		}
	});
}

export function billCancelRefund(props) {
	let that = this
	let refundData = getAllCheckedData.call(this, this.props, this.tableId, billType);//选中表体行数据信息
	ajax({
		url: '/nccloud/arap/arappub/listcancelrefund.do',
		data: refundData,
		success: (res) => {
			let { success, data } = res;
			if (success) {
				if (data.grid) {
					let grid = data.grid;
					let updateValue = [];
					for (let key in grid) {
						updateValue.push({ index: key, data: { values: grid[key].values } });
					}
					props.table.updateDataByIndexs(tableId, updateValue);
				}
				if (data.message) {
					toast({
						duration: 'infinity',
						color: data.PopupWindowStyle,
						content: data.message
					});
					that.onSelected();
				}
			}
		}
	});
}
/*Hm9gUKDDwtNjV7Mk8onAztUHq1J91LIC2ncuaDAP/5puoLckI554fGMgKidJrsa5*/